package tutorial.java.dragdrop;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.HeadlessException;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;

import java.awt.List;
import java.awt.TextArea;

import javax.swing.JTextField;

import java.awt.Dimension;

import javax.swing.AbstractListModel;

import java.awt.ScrollPane;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.ListSelectionModel;

public class ListDemo extends JFrame {

	private JPanel contentPane;
	private JTextField txtHehe;
	private JList list;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ListDemo frame = new ListDemo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ListDemo() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		list = new JList();
		list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				String value = list.getSelectedValue().toString();
				if (value != null) {
					JOptionPane.showMessageDialog(null, value);
				}
			}
		});
		list.setBounds(152, 64, 92, 99);
		contentPane.add(list);
		
		JButton btnButton = new JButton("Button");
		btnButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				
				try {
					String value = list.getSelectedValue().toString();
					if (value != null) {
						JOptionPane.showMessageDialog(null, value);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(null, "Please select one item");
				}
			}
		});
		btnButton.setBounds(152, 186, 89, 23);
		contentPane.add(btnButton);
	
		initData();
	}
	
	private void initData(){
		DefaultListModel model = new DefaultListModel();
		for (int i = 1; i <= 5; i++) {
			model.addElement("item " + i);
		}
		list.setModel(model);
	}
}
